using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using EstimateTracker.DataAccess.Repositories;
using EstimateTracker.Domain.Entities;
using EstimateTracker.Events;
using JetBrains.Annotations;
using Microsoft.Practices.Prism.Events;

namespace EstimateTracker.ViewModels
{
    public class TaskViewModel : ViewModelBase
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly ITaskRepository _taskRepository;

        private readonly ObservableCollection<Task> _tasks;
        private Task _selectedTask;

        public TaskViewModel([NotNull] IEventAggregator eventAggregator, [NotNull] ITaskRepository taskRepository)
        {
            if (eventAggregator == null) throw new ArgumentNullException("eventAggregator");
            if (taskRepository == null) throw new ArgumentNullException("taskRepository");

            _eventAggregator = eventAggregator;
            _taskRepository = taskRepository;

            _tasks = new ObservableCollection<Task>();
        }

        public ObservableCollection<Task> Tasks
        {
            get { return _tasks; }
        }

        public Task SelectedTask
        {
            get { return _selectedTask; }
            set
            {
                _selectedTask = value;
                double actuals = _selectedTask == null ? 0 :_taskRepository.FindActualsForTask(SelectedTask.Id);
                _eventAggregator.GetEvent<UpdateTaskActualsEvent>().Publish(actuals);
                OnPropertyChanged("SelectedTask");
            }
        }

        private void Bind(int? id)
        {
            Tasks.Clear();
            if (id == null) return;
            List<Task> tasks = _taskRepository.FindByActivityId(id.Value).ToList();
            tasks.ForEach(Tasks.Add);
            SelectedTask = tasks.FirstOrDefault();
        }

        public void Initialize()
        {
            _eventAggregator.GetEvent<ActivitySelectedEvent>().Subscribe(Bind);
        }

        public void AddTask(string taskName, double taskEstimate, Activity selectedActivity)
        {
            Task task = new Task{Activity = selectedActivity,Name = taskName,EstimatedHours = taskEstimate};
            Tasks.Add(task);
            _taskRepository.Save(task);
        }
    }
}